<template>
  <div class="app-container">
    <el-card shadow="never" v-loading="loading">
      <template #header>
        <div class="card-header">
          <h3>医疗记录详情</h3>
          <div class="header-actions">
            <el-button 
              type="primary" 
              v-if="recordData.status !== '已签名'"
              @click="handleEdit"
              v-permission="'medical_record:update'"
            >
              编辑
            </el-button>
            <el-button @click="goBack">返回</el-button>
          </div>
        </div>
      </template>
      
      <div v-if="recordData.id">
        <el-descriptions title="基本信息" :column="3" border>
          <el-descriptions-item label="就诊ID">{{ recordData.visitId }}</el-descriptions-item>
          <el-descriptions-item label="就诊日期">{{ formatDate(recordData.visitDate) }}</el-descriptions-item>
          <el-descriptions-item label="记录状态">
            <el-tag :type="getStatusType(recordData.status)">{{ recordData.status }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="科室">{{ recordData.departmentName }}</el-descriptions-item>
          <el-descriptions-item label="主诊医生">{{ recordData.doctorName }}</el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(recordData.createTime) }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider />
        
        <el-descriptions title="患者信息" :column="3" border>
          <el-descriptions-item label="姓名">
            <el-button type="text" @click="viewPatient(recordData.patientId)">
              {{ recordData.patientName }}
            </el-button>
          </el-descriptions-item>
          <el-descriptions-item label="性别">{{ recordData.patientInfo?.gender }}</el-descriptions-item>
          <el-descriptions-item label="年龄">{{ recordData.patientInfo?.age }}岁</el-descriptions-item>
          <el-descriptions-item label="患者ID">{{ recordData.patientInfo?.patientId }}</el-descriptions-item>
          <el-descriptions-item label="联系电话">{{ recordData.patientInfo?.phone }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{ recordData.patientInfo?.idCard }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider />
        
        <el-card class="content-card">
          <template #header>
            <div class="section-header">
              <h4>主诉与现病史</h4>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="24">
              <div class="section-label">主诉：</div>
              <div class="section-content">{{ recordData.chiefComplaint || '无' }}</div>
            </el-col>
          </el-row>
          <el-row :gutter="20" class="mt-20">
            <el-col :span="24">
              <div class="section-label">现病史：</div>
              <div class="section-content">{{ recordData.presentIllness || '无' }}</div>
            </el-col>
          </el-row>
          <el-row :gutter="20" class="mt-20">
            <el-col :span="24">
              <div class="section-label">既往史：</div>
              <div class="section-content">{{ recordData.pastHistory || '无' }}</div>
            </el-col>
          </el-row>
        </el-card>
        
        <el-card class="content-card">
          <template #header>
            <div class="section-header">
              <h4>体格检查</h4>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="6">
              <div class="exam-item">
                <span class="exam-label">血压：</span>
                <span class="exam-value">{{ recordData.physicalExam?.bloodPressure || '--' }} mmHg</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="exam-item">
                <span class="exam-label">脉搏：</span>
                <span class="exam-value">{{ recordData.physicalExam?.pulse || '--' }} 次/分</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="exam-item">
                <span class="exam-label">体温：</span>
                <span class="exam-value">{{ recordData.physicalExam?.temperature || '--' }} ℃</span>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="exam-item">
                <span class="exam-label">体重：</span>
                <span class="exam-value">{{ recordData.physicalExam?.weight || '--' }} kg</span>
              </div>
            </el-col>
            <el-col :span="6" class="mt-20">
              <div class="exam-item">
                <span class="exam-label">身高：</span>
                <span class="exam-value">{{ recordData.physicalExam?.height || '--' }} cm</span>
              </div>
            </el-col>
          </el-row>
        </el-card>
        
        <el-card class="content-card">
          <template #header>
            <div class="section-header">
              <h4>诊断与治疗</h4>
            </div>
          </template>
          <div class="section-label mb-10">诊断：</div>
          <el-table :data="recordData.diagnosis || []" style="width: 100%" border>
            <el-table-column label="诊断类型" prop="type" width="120" />
            <el-table-column label="诊断编码" prop="code" width="120" />
            <el-table-column label="诊断名称" prop="name" min-width="150" />
            <el-table-column label="诊断描述" prop="description" min-width="200" show-overflow-tooltip />
          </el-table>
          
          <el-row :gutter="20" class="mt-20">
            <el-col :span="24">
              <div class="section-label">治疗计划：</div>
              <div class="section-content">{{ recordData.treatmentPlan || '无' }}</div>
            </el-col>
          </el-row>
        </el-card>
        
        <el-card class="content-card" v-if="recordData.multimedia && recordData.multimedia.length > 0">
          <template #header>
            <div class="section-header">
              <h4>多媒体资料</h4>
            </div>
          </template>
          <el-row :gutter="20">
            <el-col :span="6" v-for="(item, index) in recordData.multimedia" :key="index">
              <el-card shadow="hover" class="media-card">
                <template #header>
                  <div class="media-header">
                    {{ item.description || `资料 ${index + 1}` }}
                  </div>
                </template>
                <div class="media-content">
                  <img 
                    v-if="item.fileType === 'image'" 
                    :src="`/api/v1/files/data/${item.fileId}`" 
                    class="media-image" 
                    @click="previewImage(item)"
                  />
                  <div v-else class="file-box" @click="downloadFile(item)">
                    <el-icon><Document /></el-icon>
                    <span>点击下载</span>
                  </div>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-card>
        
        <el-card class="content-card">
          <template #header>
            <div class="section-header">
              <h4>相关医疗记录</h4>
              <div class="header-actions">
                <el-button 
                  type="success" 
                  size="small"
                  v-if="recordData.status === '已完成'"
                  @click="handleCreatePrescription"
                  v-permission="'prescription:create'"
                >
                  开处方
                </el-button>
                <el-button 
                  type="warning" 
                  size="small"
                  v-if="recordData.status === '已完成'"
                  @click="handleCreateMedicalOrder"
                  v-permission="'medical_order:create'"
                >
                  下医嘱
                </el-button>
              </div>
            </div>
          </template>
          
          <el-tabs v-model="activeTab">
            <el-tab-pane label="处方" name="prescriptions">
              <el-table
                :data="prescriptions"
                style="width: 100%"
                v-loading="prescriptionsLoading"
                border
              >
                <el-table-column label="处方编号" prop="prescriptionId" min-width="120" />
                <el-table-column label="开具日期" min-width="120">
                  <template #default="scope">
                    {{ formatDate(scope.row.createTime) }}
                  </template>
                </el-table-column>
                <el-table-column label="类型" prop="type" width="100" />
                <el-table-column label="状态" prop="status" width="100">
                  <template #default="scope">
                    <el-tag :type="getPrescriptionStatusType(scope.row.status)">
                      {{ scope.row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="药品数量" width="100">
                  <template #default="scope">
                    {{ scope.row.items?.length || 0 }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                  <template #default="scope">
                    <el-button 
                      type="primary" 
                      size="small"
                      @click="viewPrescription(scope.row.id)"
                    >
                      查看
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-empty v-if="prescriptions.length === 0" description="暂无处方记录" />
            </el-tab-pane>
            
            <el-tab-pane label="医嘱" name="medicalOrders">
              <el-table
                :data="medicalOrders"
                style="width: 100%"
                v-loading="medicalOrdersLoading"
                border
              >
                <el-table-column label="医嘱编号" prop="orderNumber" min-width="120" />
                <el-table-column label="下达日期" min-width="120">
                  <template #default="scope">
                    {{ formatDate(scope.row.createTime) }}
                  </template>
                </el-table-column>
                <el-table-column label="类型" prop="type" width="100" />
                <el-table-column label="状态" prop="status" width="100">
                  <template #default="scope">
                    <el-tag :type="getMedicalOrderStatusType(scope.row.status)">
                      {{ scope.row.status }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="执行频次" prop="frequency" width="100" />
                <el-table-column label="操作" width="120" fixed="right">
                  <template #default="scope">
                    <el-button 
                      type="primary" 
                      size="small"
                      @click="viewMedicalOrder(scope.row.id)"
                    >
                      查看
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-empty v-if="medicalOrders.length === 0" description="暂无医嘱记录" />
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { medicalRecordAPI, prescriptionAPI, medicalOrderAPI } from '@/utils/api'
import { formatDate } from '@/utils/date'

// 路由相关
const route = useRoute()
const router = useRouter()
const recordId = ref(route.params.id)

// 数据加载状态
const loading = ref(false)
const prescriptionsLoading = ref(false)
const medicalOrdersLoading = ref(false)

// 医疗记录数据
const recordData = ref({})

// 相关处方和医嘱
const prescriptions = ref([])
const medicalOrders = ref([])
const activeTab = ref('prescriptions')

// 获取医疗记录详情
const getRecordDetail = async () => {
  loading.value = true
  try {
    const res = await medicalRecordAPI.getMedicalRecord(recordId.value)
    recordData.value = res.data
    // 获取相关处方和医嘱
    getRelatedPrescriptions()
    getRelatedMedicalOrders()
  } catch (error) {
    console.error('获取医疗记录详情失败', error)
    ElMessage.error('获取医疗记录详情失败')
  } finally {
    loading.value = false
  }
}

// 获取相关处方
const getRelatedPrescriptions = async () => {
  prescriptionsLoading.value = true
  try {
    const res = await prescriptionAPI.getPrescriptions({
      medicalRecordId: recordId.value,
      limit: 10
    })
    prescriptions.value = res.data.prescriptions || []
  } catch (error) {
    console.error('获取相关处方失败', error)
  } finally {
    prescriptionsLoading.value = false
  }
}

// 获取相关医嘱
const getRelatedMedicalOrders = async () => {
  medicalOrdersLoading.value = true
  try {
    const res = await medicalOrderAPI.getMedicalOrders({
      medicalRecordId: recordId.value,
      limit: 10
    })
    medicalOrders.value = res.data.medicalOrders || []
  } catch (error) {
    console.error('获取相关医嘱失败', error)
  } finally {
    medicalOrdersLoading.value = false
  }
}

// 获取状态标签类型
const getStatusType = (status) => {
  switch (status) {
    case '草稿':
      return ''
    case '已完成':
      return 'success'
    case '已签名':
      return 'primary'
    default:
      return 'info'
  }
}

// 获取处方状态标签类型
const getPrescriptionStatusType = (status) => {
  switch (status) {
    case '待审核':
      return 'warning'
    case '已审核':
      return 'success'
    case '已发药':
      return 'primary'
    case '已作废':
      return 'danger'
    default:
      return 'info'
  }
}

// 获取医嘱状态标签类型
const getMedicalOrderStatusType = (status) => {
  switch (status) {
    case '待执行':
      return 'warning'
    case '执行中':
      return 'primary'
    case '已完成':
      return 'success'
    case '已终止':
      return 'danger'
    default:
      return 'info'
  }
}

// 查看患者
const viewPatient = (patientId) => {
  router.push(`/patients/detail/${patientId}`)
}

// 查看处方
const viewPrescription = (id) => {
  router.push(`/prescriptions/detail/${id}`)
}

// 查看医嘱
const viewMedicalOrder = (id) => {
  router.push(`/medical-orders/detail/${id}`)
}

// 编辑医疗记录
const handleEdit = () => {
  router.push(`/medical-records/edit/${recordId.value}`)
}

// 创建处方
const handleCreatePrescription = () => {
  router.push({
    path: '/prescriptions/create',
    query: {
      patientId: recordData.value.patientId,
      medicalRecordId: recordData.value.id,
      doctorId: recordData.value.doctorId,
      departmentId: recordData.value.departmentId
    }
  })
}

// 创建医嘱
const handleCreateMedicalOrder = () => {
  router.push({
    path: '/medical-orders/create',
    query: {
      patientId: recordData.value.patientId,
      medicalRecordId: recordData.value.id,
      doctorId: recordData.value.doctorId,
      departmentId: recordData.value.departmentId
    }
  })
}

// 图片预览
const previewImage = (item) => {
  window.open(`/api/v1/files/data/${item.fileId}`, '_blank')
}

// 下载文件
const downloadFile = (item) => {
  window.open(`/api/v1/files/download/${item.fileId}`, '_blank')
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 页面加载时获取数据
onMounted(() => {
  getRecordDetail()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.content-card {
  margin-top: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.section-label {
  font-weight: bold;
  margin-bottom: 5px;
}

.section-content {
  line-height: 1.6;
  white-space: pre-line;
}

.exam-item {
  display: flex;
  align-items: center;
}

.exam-label {
  font-weight: bold;
  margin-right: 10px;
}

.media-card {
  height: 200px;
  margin-bottom: 20px;
}

.media-header {
  font-size: 14px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.media-content {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 140px;
  overflow: hidden;
}

.media-image {
  max-width: 100%;
  max-height: 100%;
  cursor: pointer;
}

.file-box {
  display: flex;
  flex-direction: column;
  align-items: center;
  cursor: pointer;
}

.file-box .el-icon {
  font-size: 40px;
  margin-bottom: 10px;
}

.mb-10 {
  margin-bottom: 10px;
}

.mt-20 {
  margin-top: 20px;
}
</style> 